import 'dart:convert';

import 'package:chi_med_det_flutter/url.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class SignupPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SignupPageState();
}

class _SignupPageState extends State<SignupPage> {
  final GlobalKey<FormState> signupKey = GlobalKey();
  String _account = "";
  String _password = "";
  String _confirmPass = "";

  void showSnackBar(String content) {
    final snackBar = SnackBar(
      content: Text(content),
      duration: Duration(seconds: 3),
      action: SnackBarAction(label: "知道了", onPressed: () {}),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  void onSubmit() {
    final signupForm = signupKey.currentState;
    signupForm?.save();
    if (signupForm != null && signupForm.validate()) {
      if (_account.length > 0 &&
          _password.length > 0 &&
          _confirmPass.length > 0) {
        doSubmit();
      } else {
        showSnackBar("注册账号与密码均不能为空");
      }
    }
  }

  void doSubmit() {
    final url = Uri.parse(URL.SIGNUP);
    http
        .post(
          url,
          headers: const {'Content-Type': 'application/json'},
          body: jsonEncode({
            'account': _account,
            'password': _password,
            'confirmPass': _confirmPass,
          }),
        )
        .then(
          (http.Response response) {
            Map<String, dynamic> res = jsonDecode(response.body);
            if (res['code'] == 0) {
              showSnackBar(res['msg']);
            } else {
              showSnackBar(res['msg']);
            }
          },
          onError: (err) {
            print("onError, err=${err}");
            showSnackBar(err);
          },
        );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text('新用户注册', style: TextStyle(fontWeight: FontWeight.bold)),
      ),
      body: Center(
        child: FractionallySizedBox(
          widthFactor: .6,
          child: Center(
            child: Form(
              key: signupKey,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextFormField(
                    maxLength: 12,
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.person),
                      labelText: '请输入账号',
                      suffixIcon: Tooltip(
                        message: '账号由英文字母、数字及下划线组成，且长度在6-12之间',
                        child: Icon(Icons.help),
                      ),
                    ),
                    onSaved: (String? account) {
                      if (account != null) {
                        _account = account.trim();
                      }
                    },
                    validator: (String? account) {
                      if (account != null && account.trim().length > 0) {
                        final accountPattern = RegExp(r"^[a-zA-Z]\w{5,11}$");
                        return accountPattern.hasMatch(account.trim())
                            ? null
                            : "注册账号不符合要求";
                      }
                      return null;
                    },
                  ),
                  TextFormField(
                    obscureText: true,
                    maxLength: 12,
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.lock),
                      labelText: '请输入密码',
                      suffixIcon: Tooltip(
                        message: '密码须由字母与数字组成，且长度在6-12之间',
                        child: Icon(Icons.help),
                      ),
                    ),
                    onSaved: (String? password) {
                      if (password != null) {
                        _password = password.trim();
                      }
                    },
                    validator: (String? password) {
                      if (password != null && password.trim().length > 0) {
                        final passwordPattern = RegExp(
                          r"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,12}$",
                        );
                        return passwordPattern.hasMatch(password.trim())
                            ? null
                            : "输入密码不符合要求";
                      }
                      return null;
                    },
                  ),
                  TextFormField(
                    obscureText: true,
                    maxLength: 12,
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.lock),
                      labelText: '请确认密码',
                      suffixIcon: Tooltip(
                        message: '确认密码需要与输入密码保持一致',
                        child: Icon(Icons.help),
                      ),
                    ),
                    onSaved: (String? confirmPass) {
                      if (confirmPass != null) {
                        _confirmPass = confirmPass.trim();
                      }
                    },
                    validator: (String? password) {
                      if (_password != _confirmPass) {
                        return "确认密码不符合要求";
                      }
                      return null;
                    },
                  ),
                  SizedBox(height: 20),
                  TextButton(
                    onPressed: () {
                      onSubmit();
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 20),
                      child: Text(
                        "提交",
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 18,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    style: ButtonStyle(
                      foregroundColor: WidgetStateProperty.all(Colors.black),
                      backgroundColor: WidgetStateProperty.resolveWith<Color>((
                        Set<WidgetState> states,
                      ) {
                        if (states.contains(WidgetState.pressed)) {
                          return Colors.grey;
                        }
                        return Colors.purple;
                      }),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
